package transactions.dq.mail;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import dinamica.StringUtil;

public class SimpleMail
{
	
	/**
	 * Send a simple text message using a background thread
	 * @param host Mail server address
	 * @param host Mail server port
	 * @param from valid email address
	 * @param from valid email pass
	 * @param fromName Descriptive from name
	 * @param to valid email address
	 * @param subject Email subject
	 * @param body Message body (text only)
	 * @param to valid cc email address
	 * @param email parts
	 */

	public void send(String host, String port, String from, String fromPass, String fromName, String to, String subject, String body, String cc, Vector<String> file)
	{
		Thread t = new Thread(new BackgroundSender(host, port, from, fromPass, fromName, to, subject, body, cc, file));
		t.start();
	}

	class BackgroundSender implements Runnable
	{

		String host = null;
		String port = null;
		String from = null;
		String fromPass = null;
		String fromName = null;
		String to = null;
		String subject = null;
		String body = null;
		String cc = null;
		Vector<String> file = null; //用于保存发送附件的文件名的集合
		
		public BackgroundSender(String host, String port, String from, String fromPass, String fromName, String to, String subject, String body, String cc, Vector<String> file)
		{
			this.host = host;
			this.port = port;
			this.from = from;
			this.fromPass = fromPass;
			this.fromName = fromName;
			this.to = to;
			this.subject = subject;
			this.body = body==null?"":body;
			this.cc = cc;
			this.file = file;
		}
		
		public void run()
		{
			
			try
			{
				//init email system
				Properties props = System.getProperties();
				props.put( "mail.smtp.host", host );
				props.put("mail.smtp.auth", "true");
				props.put("mail.debug", "true");
				props.put("mail.smtp.port", port);
				props.put("mail.smtp.socketFactory.port", port);
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
				props.put("mail.smtp.socketFactory.fallback", "false");
				Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(from, fromPass);
					}
				});
				//Session session = Session.getDefaultInstance( props, null );
				session.setDebug( false );
				
				String recipients[] = null;
				if (to.indexOf(",")>0) {
					recipients = StringUtil.split(to, ",");
				} else {
					recipients = new String[1];
					recipients[0] = to;
				}
				
				for (int i = 0; i < recipients.length; i++) {

					//recipients
					InternetAddress[] toAddrs = InternetAddress.parse( recipients[i], false );
					
					//create message
					Message msg = new MimeMessage( session );
					msg.setRecipients( Message.RecipientType.TO, toAddrs );
					
					if (cc!=null) {
						InternetAddress[] toCC = InternetAddress.parse( cc, false );
						msg.setRecipients( Message.RecipientType.CC, toCC );
					}
					
					msg.setSubject( subject );
					msg.setFrom( new InternetAddress( from, fromName ) );
					msg.setText( body );
					msg.setSentDate(new Date());
					
					//发送附件
					if(file != null && !file.isEmpty()){//有附件  
						Multipart mp = new MimeMultipart();  
						MimeBodyPart mbp = new MimeBodyPart();  
						Enumeration<String> efile = file.elements();  
						while(efile.hasMoreElements()){   
							mbp=new MimeBodyPart();  
							String filename = efile.nextElement(); //选择出每一个附件名  
							FileDataSource fds = new FileDataSource(filename); //得到数据源  
							mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart  
							String fn = fds.getName();
							try {
								fn = MimeUtility.encodeText(fn);
							}catch (UnsupportedEncodingException e){
								e.printStackTrace();
							}
						    mbp.setFileName(fn); 
							mp.addBodyPart(mbp);  
						}
						msg.setContent(mp);
						file.removeAllElements();
					}
					
					//send 
					Transport.send( msg );
					
				}
				
			}
			catch (Throwable e)
			{
				try
				{
					String d = StringUtil.formatDate(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");
					System.err.println("ERROR [dinamica.SimpleMail@" + d + "]: " + e.getMessage() + " recipient(s): " + to);
				}
				catch (Throwable e1)
				{
				}
			}
			
		}
		
	}

}
